/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.core.service.base.impl;

import cn.simastudio.talos.common.constants.SimaConstants;
import cn.simastudio.talos.core.aop.annotation.Logging;
import cn.simastudio.talos.core.enums.UserStatus;
import cn.simastudio.talos.core.exception.auth.UserBlockedAuthException;
import cn.simastudio.talos.core.exception.auth.UserNotExistsAuthException;
import cn.simastudio.talos.core.exception.auth.UserPasswordNotMatchAuthException;
import cn.simastudio.talos.core.mapper.base.RoleMapper;
import cn.simastudio.talos.core.mapper.base.UserMapper;
import cn.simastudio.talos.core.mapper.base.UserRoleRelMapper;
import cn.simastudio.talos.core.model.base.User;
import cn.simastudio.talos.core.model.base.UserRoleRel;
import cn.simastudio.talos.core.service.base.UserService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@SuppressWarnings("SpringJavaAutowiringInspection")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private UserRoleRelMapper userRoleRelMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public User getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }

    @Logging(description = "login")
    @Override
    public User login(String username, String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new UserNotExistsAuthException();
        }
        // 密码不在系统设置的长度范围内，登录失败
        if (password.length() < SimaConstants.PASSWORD_MIN_LENGTH || password.length() > SimaConstants.PASSWORD_MAX_LENGTH) {
            throw new UserPasswordNotMatchAuthException();
        }

        User user = null;

        //此处需要走代理对象，目的是能走缓存切面
        UserService proxyUserService = (UserService) AopContext.currentProxy();
        if (judgeUsername(username)) {
            user = proxyUserService.getUserByUsername(username);
        }

        if (user == null || UserStatus.Deleted.getValue().equals(user.getStatus())) {
            throw new UserNotExistsAuthException();
        }

        passwordService.validate(user, password);

        if (UserStatus.Locked.getValue().equals(user.getStatus())) {
            throw new UserBlockedAuthException("Get latest reason for why user blocked");
        }

        return user;
    }

    @Override
    public User create(User user) {
        //加密用户密码
        passwordService.encryptPassword(user);
        //插入新用户
        int userKey = userMapper.insertSelective(user);

        //添加系统用户和角色的关联
        // TODO:添加管理员,ID配置
        UserRoleRel userRoleRel = new UserRoleRel();
        userRoleRel.setRoleId(2);
        userRoleRel.setRemark("Admin");
        userRoleRel.setUserId(user.getId());
        userRoleRelMapper.insert(userRoleRel);
        return user;
    }

    @Override
    public List<User> getUserList(User user) {
        return userMapper.getUserList(user);
    }

    @Override
    public User getUserRoleDetail(Integer id) {
        return userMapper.getUserRoleDetail(id);
    }

    @Override
    public int updateUser(User user) {
        if (user.getPassword() != null && user.getUsername() != null) {
            passwordService.encryptPassword(user);
        } else {
            user.setPassword(null);
        }
        return userMapper.updateByPrimaryKeySelective(user);
    }

    private boolean judgeUsername(String username) {
        //如果用户名不在指定范围内也是错误的
        return !(username.length() < SimaConstants.USERNAME_MIN_LENGTH || username.length() > SimaConstants.USERNAME_MAX_LENGTH);
    }
}
